<script lang="ts" setup>
import type { InfraConfigApi } from '#/api/infra/config';

import { onMounted, ref } from 'vue';

import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import {
  Alert,
  Button,
  Card,
  Form,
  Input,
  message,
  Select,
} from 'ant-design-vue';

import { list, updateBatch } from '#/api/infra/config';

// 定义地图配置类型
interface MapConfig {
  amap_key?: InfraConfigApi.Config;
  amap_security_js_code?: InfraConfigApi.Config;
  amap_version?: InfraConfigApi.Config;
  amap_plugins?: InfraConfigApi.Config;
  amap_default_city?: InfraConfigApi.Config;
  amap_default_zoom?: InfraConfigApi.Config;
  map_provider?: InfraConfigApi.Config; // 新增：地图服务商，支持 amap, baidu, tencent
  baidu_map_key?: InfraConfigApi.Config; // 百度地图密钥
  tencent_map_key?: InfraConfigApi.Config; // 腾讯地图密钥
}

// 状态管理
const formRef = ref<any>(null);
const loading = ref(false);
const isUpdate = ref(false);

// 表单数据
const formData = ref({
  amap_key: '',
  amap_security_js_code: '',
  amap_version: '2.0',
  amap_plugins: 'AMap.Geocoder,AMap.PlaceSearch,AMap.Marker',
  amap_default_city: '全国',
  amap_default_zoom: '13',
  map_provider: 'amap', // 新增：地图服务商，支持 amap, baidu, tencent
  baidu_map_key: '', // 百度地图密钥
  tencent_map_key: '', // 腾讯地图密钥
});

const oldForm = ref({ ...formData.value });

const configList = ref<MapConfig>({
  amap_key: { name: '高德地图API Key' },
  amap_security_js_code: { name: '高德地图安全密钥' },
  amap_version: { name: '高德地图版本' },
  amap_plugins: { name: '高德地图插件' },
  amap_default_city: { name: '默认城市' },
  amap_default_zoom: { name: '默认缩放级别' },
  map_provider: { name: '地图服务商' },
  baidu_map_key: { name: '百度地图密钥' },
  tencent_map_key: { name: '腾讯地图密钥' },
});

const queryForm = {
  category: 'MAP',
};

// 页面初始化
onMounted(() => {
  getConfig();
});

const getConfig = async () => {
  loading.value = true;
  try {
    const data = await list(queryForm);
    if (data && data.length > 0) {
      const configList = data.reduce(
        (obj: MapConfig, option: InfraConfigApi.Config) => {
          obj[option.key] = { ...option };
          formData.value[option.key] = option.value;
          oldForm.value[option.key] = option.value;
          return obj;
        },
        {},
      );
      // 根据key 和原有的configList 合并
      configList.value = { ...configList.value, ...configList };
    }
  } catch {
    message.error('加载地图配置信息失败');
  } finally {
    loading.value = false;
  }
};

const handleUpdate = () => {
  isUpdate.value = true;
};

const handleCancel = () => {
  isUpdate.value = false;
  formData.value = { ...oldForm.value };
};

const handleSave = async () => {
  const hideLoading = message.loading({
    content: '保存地图配置中...',
    duration: 0,
  });
  try {
    console.log(formData.value);
    const updateList = Object.entries(formData.value).map(([key, value]) => {
      return {
        id: configList.value[key]?.id,
        key,
        value,
        name: configList.value[key]?.name,
        visible: false,
        category: 'MAP',
        type: 1,
        remark: configList.value[key]?.remark,
      } as InfraConfigApi.Config;
    });
    await updateBatch(updateList);
    message.success('地图配置保存成功');
    oldForm.value = { ...formData.value };
    isUpdate.value = false;
  } catch {
    message.error('地图配置保存失败');
  } finally {
    hideLoading();
  }
};

const handleReset = () => {
  formData.value = {
    amap_key: '',
    amap_security_js_code: '',
    amap_version: '2.0',
    amap_plugins: 'AMap.Geocoder,AMap.PlaceSearch,AMap.Marker',
    amap_default_city: '全国',
    amap_default_zoom: '13',
    map_provider: 'amap', // 新增：地图服务商，支持 amap, baidu, tencent
    baidu_map_key: '', // 百度地图密钥
    tencent_map_key: '', // 腾讯地图密钥
  };
};
</script>

<template>
  <Page style="width: 80%; margin: 0 auto">
    <Card title="高德地图配置">
      <Alert
        message="注意：请确保您已经在高德开放平台注册了开发者账号并创建了应用，获取相应的API Key和安全密钥。"
        type="info"
        show-icon
        style="margin-bottom: 16px"
      />

      <Form
        ref="formRef"
        :model="formData"
        label-align="left"
        :disabled="!isUpdate"
        :label-col="{ span: 4 }"
      >
        <Form.Item label="地图服务商" name="map_provider">
          <Select
            v-model:value="formData.map_provider"
            placeholder="请选择地图服务商"
          >
            <Select.Option value="amap">高德地图</Select.Option>
            <Select.Option value="baidu">百度地图</Select.Option>
            <Select.Option value="tencent">腾讯地图</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="高德地图API Key"
          name="amap_key"
          :rules="[{ required: true, message: '请输入高德地图API Key' }]"
          v-if="formData.map_provider === 'amap'"
        >
          <Input
            v-model:value="formData.amap_key"
            placeholder="请输入高德地图API Key"
          />
        </Form.Item>
        <!-- 百度地图配置 -->
        <Form.Item
          label="百度地图密钥"
          name="baidu_map_key"
          :rules="[{ required: true, message: '请输入百度地图密钥' }]"
          v-if="formData.map_provider === 'baidu'"
        >
          <Input
            v-model:value="formData.baidu_map_key"
            placeholder="请输入百度地图密钥"
          />
        </Form.Item>
        <!-- 腾讯地图配置 -->
        <Form.Item
          label="腾讯地图密钥"
          name="tencent_map_key"
          :rules="[{ required: true, message: '请输入腾讯地图密钥' }]"
          v-if="formData.map_provider === 'tencent'"
        >
          <Input
            v-model:value="formData.tencent_map_key"
            placeholder="请输入腾讯地图密钥"
          />
        </Form.Item>

        <Form.Item
          label="高德地图安全密钥"
          name="amap_security_js_code"
          :rules="[{ required: true, message: '请输入高德地图安全密钥' }]"
          v-if="formData.map_provider === 'amap'"
        >
          <Input
            v-model:value="formData.amap_security_js_code"
            placeholder="请输入高德地图安全密钥"
          />
        </Form.Item>

        <Form.Item label="地图版本" name="amap_version">
          <Input
            v-model:value="formData.amap_version"
            placeholder="请输入地图版本"
          />
        </Form.Item>

        <Form.Item label="地图插件" name="amap_plugins">
          <Input
            v-model:value="formData.amap_plugins"
            placeholder="请输入地图插件，多个插件用逗号分隔"
          />
        </Form.Item>

        <Form.Item label="默认城市" name="amap_default_city">
          <Input
            v-model:value="formData.amap_default_city"
            placeholder="请输入默认城市"
          />
        </Form.Item>

        <Form.Item label="默认缩放级别" name="amap_default_zoom">
          <Input
            v-model:value="formData.amap_default_zoom"
            placeholder="请输入默认缩放级别 (1-20)"
          />
        </Form.Item>
      </Form>

      <div style="margin-top: 24px; text-align: center">
        <Button
          v-if="!isUpdate"
          type="primary"
          @click="handleUpdate"
          style="margin-right: 8px"
        >
          <IconifyIcon icon="mdi:edit" />
          编辑配置
        </Button>
        <template v-else>
          <Button type="primary" @click="handleSave" style="margin-right: 8px">
            <IconifyIcon icon="mdi:content-save" />
            保存配置
          </Button>
          <Button @click="handleCancel" style="margin-right: 8px">
            <IconifyIcon icon="mdi:close" />
            取消
          </Button>
          <Button @click="handleReset">
            <IconifyIcon icon="mdi:refresh" />
            重置
          </Button>
        </template>
      </div>
    </Card>

    <Card title="配置说明" style="margin-top: 16px">
      <div style="line-height: 1.8">
        <h4>高德地图配置说明：</h4>
        <ul>
          <li>
            <strong>API Key：</strong
            >在高德开放平台创建应用后获取的Key，用于调用地图API
          </li>
          <li>
            <strong>安全密钥：</strong
            >用于增强API调用的安全性，防止Key被滥用。如果出现"INVALID_USER_SCODE"错误，请检查安全密钥是否正确配置
          </li>
          <li><strong>地图版本：</strong>建议使用最新版本2.0</li>
          <li><strong>地图插件：</strong>需要加载的插件，多个插件用逗号分隔</li>
          <li>
            <strong>默认城市：</strong>地图初始化时显示的城市，默认为"全国"
          </li>
          <li>
            <strong>默认缩放级别：</strong
            >地图初始化时的缩放级别，范围1-20，默认为13
          </li>
        </ul>

        <h4 style="margin-top: 16px">使用说明：</h4>
        <ul>
          <li>配置完成后，在学校管理中的地图定位字段将使用此配置</li>
          <li>用户可以通过搜索地址或点击地图来选择位置</li>
          <li>选择的位置会保存为经纬度和地址信息</li>
        </ul>

        <h4 style="margin-top: 16px">获取方式：</h4>
        <ol>
          <li>
            访问
            <a
              href="https://lbs.amap.com/"
              target="_blank"
              class="text-blue-500"
              >高德开放平台</a
            >
          </li>
          <li>注册开发者账号并登录</li>
          <li>创建新应用，选择"Web端"</li>
          <li>获取API Key和安全密钥</li>
          <li>将获取的Key和密钥填写到上方表单中</li>
        </ol>
      </div>
    </Card>
  </Page>
</template>
